package com.palm.vue;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Vue3Compressor {
    private static Pattern importPattern = Pattern.compile("import\\s+([\\{\\w\\,\\}\\s]+\\s+from\\s+)?(['\"][\\.\\-\\/\\w]+['\"])", Pattern.DOTALL);

    public String compile(String source, String path) {
        StringBuilder sb = new StringBuilder();
        sb.append("define([" + String.join(",", getRequireModules(source)) + "],(compiler)=>{");
        //处理导入
        source = source.replaceAll("`", "\\`");
        sb.append("const src=`" + source + "`");
        sb.append("\nconst path=`" + path + "`");
        sb.append("\nconst dest=compiler(src,path)");
        sb.append("\nconst define=function(fun){return fun(require)};return eval(dest)");
        sb.append("})");
        return sb.toString();
    }

    private List<String> getRequireModules(String source) {
        List<String> imports = new ArrayList<>();
        imports.add("'compiler'");
        Matcher importMatcher = importPattern.matcher(source);
        StringBuffer sb = new StringBuffer();
        while (importMatcher.find()) {
            String g2 = importMatcher.group(2);
            if (g2 != null) {
                g2 = g2.trim().replaceAll("(^\")|(\"$)", "'");
                imports.add(g2);
                //importMatcher.appendReplacement(sb, "require(" + g2 + ")");
            }
        }
        return imports;
    }
}
